using System;
using System.Collections.Generic;
using System.Linq;
using QAssetBundle;
using UnityEngine;
using QFramework;

namespace QFramework.Monk
{
	public partial class SimpleKnife : AbilityBase
	{
		public override void InitAbility()
		{
			//mLevel = 0;//默认解锁
			mRadius = 10;
			//this.Show();
			//base.ShowAbility();
		}
		private void Update()
		{
			if (!AppStart.CheckGameState(GameState.GamePlaying))
			{
				return;
			}
			mCurTime+=Time.deltaTime;
			if (mCurTime > AppStart.ackDuration.Value)
			{
				var enemys = FindNearestEnemies();
				if (enemys.Count>0)
				{
					foreach (var enemy in enemys)
					{
						if (enemy!=null)
						{
							AudioKit.PlaySound(Sxf.KNIFE);
							CreateKnife(enemy);
						}
					}

				}

				mCurTime = 0;
			}
		}

		private void CreateKnife(EnemyBase enemy)
		{
			Knife.Instantiate().Position(transform.position).Show().Self(self =>
			{
				var selfCache = self;
				var  direction = (enemy.transform.position - transform.position).normalized;
				selfCache.transform.up = direction;
				selfCache.velocity = direction * mSpeed * 8;
			
				selfCache.OnTriggerEnter2DEvent(collider2D =>
				{
					if (collider2D.gameObject.layer == LayerMask.NameToLayer("Enemy"))
					{
						var enemy = collider2D.GetComponentInParent<EnemyBase>();
						if (enemy != null)
						{
							enemy.CostHp(AppStart.damage.Value);
							//是否可穿透
							if (!mIsSuper)
							{
								selfCache.gameObject.DestroySelfGracefully();

							}
						}
					}

				}).UnRegisterWhenGameObjectDestroyed(selfCache.gameObject);

				ActionKit.OnUpdate.Register(() =>
					{
						if (Player.Default!= null)
						{
							float distance =(Player.Default.Position()-self.Position()).magnitude;
							if (distance > 20)
							{
								self.gameObject.DestroySelfGracefully();
							}
							
						}

					}).UnRegisterWhenGameObjectDestroyed(self.gameObject);

			});
					
			
		}
	}
}
